package org.study.solr.boot.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.study.solr.boot.constant.SolrConstants;
import org.study.solr.boot.entity.Product;
import org.study.solr.boot.entity.ProductVO;
import org.study.solr.boot.util.SolrUtils;

import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;

/**
 * 参考 https://zhuanlan.zhihu.com/p/141035985
 *
 * @author Administrator
 * @date 2022-09-26
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private SolrClient solrClient;

    @Override
    public int addProduct1(Product product) {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id", product.getId());
        document.addField("name", product.getName());
        document.addField("picUrl", product.getPicUrl());
        document.addField("sellingPrice", product.getSellingPrice());
        document.addField("salesVolume", product.getSalesVolume());
        UpdateResponse response = null;
        try {
            response = solrClient.add(SolrConstants.collection, document);
            if (response.getStatus() == 0) {
                solrClient.commit(SolrConstants.collection);
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.getStatus();
    }

    @Override
    public int addProduct2(Product product) {
        UpdateResponse response = null;
        try {
            response = solrClient.addBean(SolrConstants.collection, product);
            if (response.getStatus() == 0) {
                solrClient.commit(SolrConstants.collection);
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.getStatus();
    }

    @Override
    public int deleteProduct(String id) {
        UpdateResponse response = null;
        try {
            response = solrClient.deleteById(SolrConstants.collection, id);
            if (response.getStatus() == 0) {
                solrClient.commit(SolrConstants.collection);
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.getStatus();
    }

    @Override
    public List<ProductVO> searchByName(String name) {
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        if (StringUtils.isNotBlank(name)) {
            query.setQuery("name:" + name);
            // 设置查询的域
            query.set("df", "name");
        }
        query.setHighlight(true);
        // 设置高亮显示的标签
        query.setHighlightSimplePre("<font color=\"red\">");
        query.setHighlightSimplePost("</font>");
        query.addHighlightField("name");
        // 高亮的标题长度
        query.setHighlightFragsize(150);
        // 获取高亮分片数，一般搜索词可能分布在文章中的不同位置，其所在一定长度的
        query.setHighlightSnippets(1);
        // 语句即为一个片段，默认为1，但根据业务需要有时候需要多取出几个分片
        List<ProductVO> list = new ArrayList<>();
        try {
            QueryResponse response = solrClient.query(SolrConstants.collection, query);
            // list = response.getBeans(ProductVO.class);
            // list = solrClient.getBinder().getBeans(ProductVO.class, response.getResults());
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            if (response.getStatus() == 0) {
                response.getResults().forEach(new Consumer<SolrDocument>() {
                    @Override
                    public void accept(SolrDocument document) {
                        ProductVO productVO = new ProductVO();
                        productVO.setId(SolrUtils.toString(document.getFieldValue("id")));
                        productVO.setName(SolrUtils.toString(document.getFieldValue("name")));
                        productVO.setPicUrl(SolrUtils.toString(document.getFieldValue("picUrl")));
                        productVO.setSellingPrice(SolrUtils.toBigDecimal(document.getFieldValue("sellingPrice")));
                        productVO.setSalesVolume(SolrUtils.toLong(document.getFieldValue("salesVolume")));
                        Map<String, List<String>> map = highlighting.get(document.getFieldValue("id"));
                        List<String> result = map.get("name");
                        if (result != null && result.size() > 0) {
                            productVO.setName(SolrUtils.toString(result.get(0)));
                        } else {
                            productVO.setName(SolrUtils.toString(document.getFieldValue("name")));
                        }
                        list.add(productVO);
                    }
                });
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
